﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="EMA.cs" company="">
//   
// </copyright>
// <summary>
//   The ema.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System;
using Systemathics.FrameWork;

namespace Systemathics.Indicators
{

    [Serializable]
    public sealed class EMA : Indicator
    {
        private readonly Decimal Alpha;
        public int Length { get; private set; }

        public EMA(Instrument instr, Data dt, BarType bt, int value, int length)
            : base(instr, dt, bt, value)
        {
            Length = length;
            Alpha = new decimal(2 / (double)(length + 1)); ;
        }



        protected override void Calculate(object price)
        {
            if (price is Bar)
            {
                var bar = price as Bar;
                Calculate(bar.BeginTime, bar.Median);
            }
            else if (price is Quote)
            {
                var quote = price as Quote;
                Calculate(quote.Time, quote.Mid);
            }
            else
            {
                var trade = price as Trade;
                Calculate(trade.Time, trade.Price);
            }
        }

        private void Calculate(DateTime time, Decimal value)
        {
            if (Count() < 2)
                Add(time, value);
            else
            {
                Add(time, Ago(0) + Alpha*(value - Ago(0)));
                IndicatorCalculated(this);
            }
        }
    }
}